package com.linsen.core.common.util;

import com.google.common.io.Resources;
import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeReader;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import lombok.experimental.UtilityClass;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.Hashtable;

/** 二维码工具类 */
@UtilityClass
public final class QREncode {
    /**
     * 读二维码并输出携带的信息
     */
    public String readQrCode(InputStream inputStream) throws IOException {
        //从输入流中获取字符串信息
        BufferedImage image = ImageIO.read(inputStream);
        //将图像转换为二进制位图源
        LuminanceSource source = new BufferedImageLuminanceSource(image);
        BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
        QRCodeReader reader = new QRCodeReader();
        com.google.zxing.Result result = null ;
        try {
            result = reader.decode(bitmap);
        } catch (ReaderException e) {
            e.printStackTrace();
        }
        return result.getText();
    }


    private final int BLACK = 0xFF000000;
    private final int WHITE = 0xFFFFFFFF;

    public BufferedImage toBufferedImage(BitMatrix matrix, boolean hasLogo) throws IOException {
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
            }
        }
        if (hasLogo){
            LogoConfig logoConfig = new LogoConfig();
            try {
                URL resource = Resources.getResource("img/logo.png");
                InputStream is = Resources.asByteSource(resource).openBufferedStream();
                addLogo_QRCode(image,is,logoConfig);
            }catch (Exception e){

            }
        }

        return image;
    }
    /**
     * 二维码图片加入Logo
     *
     * @param bim 图片流
     * @param logoPic Logo图片物理位置
     * @param logoConfig Logo图片设置參数
     * @throws Exception 异常上抛
     */
    private void addLogo_QRCode(BufferedImage bim, InputStream logoPic, LogoConfig logoConfig) {
        try {
            // 对象流传输
            BufferedImage image = bim;
            Graphics2D g = image.createGraphics();

            // 读取Logo图片
            BufferedImage logo = ImageIO.read(logoPic);

            // 设置logo的大小,本人设置为二维码图片的30%,由于过大会盖掉二维码
            int widthLogo = Math.min(logo.getWidth(null), image.getWidth() * 3 / 10), heightLogo = logo
                    .getHeight(null) > image.getHeight() * 3 / 10 ?
                    (image.getHeight() * 3 / 10) : logo.getWidth(null);

            // 计算图片放置位置
            // logo放在中心
            int x = (image.getWidth() - widthLogo) / 2;
            int y = (image.getHeight() - heightLogo) / 2;
            // 開始绘制图片
            g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g.drawImage(logo.getScaledInstance(widthLogo,heightLogo,Image.SCALE_SMOOTH), x, y, widthLogo, heightLogo, null);
            g.drawRoundRect(x, y, widthLogo, heightLogo, 15, 15);
            g.setStroke(new BasicStroke(logoConfig.getBorder()));
            g.setColor(logoConfig.getBorderColor());
            RoundRectangle2D roundedRectangle = new RoundRectangle2D.Float(x, y, widthLogo, heightLogo, 10, 10);
            g.draw(roundedRectangle);

            g.dispose();
            logo.flush();
            image.flush();

        } catch (Exception e) {
            e.getMessage();
        }
    }

    public void writeToFile(BitMatrix matrix, String format, File file, boolean hasLogo)
            throws IOException {
        BufferedImage image = toBufferedImage(matrix,hasLogo);
        if (!ImageIO.write(image, format, file)) {
            throw new IOException("Could not write an image of format " + format + " to " + file);
        }
    }


    public void writeToStream(BitMatrix matrix, String format, OutputStream stream, boolean hasLogo)
            throws IOException {
        BufferedImage image = toBufferedImage(matrix,hasLogo);
        if (!ImageIO.write(image, format, stream)) {
            throw new IOException("Could not write an image of format " + format);
        }
    }

    public void createQrCode(File outputFile, String content, int qrCodeSize, String imageFormat) throws WriterException, IOException {
        createQrCode(outputFile,content,qrCodeSize,imageFormat,false);
    }
    /**
     * 生成包含字符串信息的二维码图片
     * @param outputFile 输出文件
     * @param content 二维码携带信息
     * @param qrCodeSize 二维码图片大小(正方形边长)
     * @param imageFormat 二维码的格式
     * @param hasLogo 是否包含Logo
     * @throws WriterException
     * @throws IOException
     */
    public void createQrCode(File outputFile, String content, int qrCodeSize, String imageFormat, boolean hasLogo) throws WriterException, IOException {
        Hashtable hints = new Hashtable();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        hints.put(EncodeHintType.MARGIN, 1);
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);

        BitMatrix bitMatrix = new MultiFormatWriter().encode(content,
                BarcodeFormat.QR_CODE, qrCodeSize, qrCodeSize, hints);

        writeToFile(bitMatrix, imageFormat, outputFile, hasLogo);
    }

    public void createQrCode(OutputStream stream, String content, int qrCodeSize, String imageFormat) throws WriterException, IOException {
        createQrCode(stream,content,qrCodeSize,imageFormat,false);
    }

    /**
     * 生成包含字符串信息的二维码图片
     * @param stream 输出流
     * @param content 二维码携带信息
     * @param qrCodeSize 二维码图片大小(正方形边长)
     * @param imageFormat 二维码的格式
     * @param hasLogo 是否包含Logo
     * @throws WriterException
     * @throws IOException
     */
    public void createQrCode(OutputStream stream, String content, int qrCodeSize, String imageFormat, boolean hasLogo) throws WriterException, IOException {
        Hashtable hints = new Hashtable();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        hints.put(EncodeHintType.MARGIN, 1);
        hints.put(EncodeHintType.ERROR_CORRECTION,ErrorCorrectionLevel.H);

        BitMatrix bitMatrix = new MultiFormatWriter().encode(content,
                BarcodeFormat.QR_CODE, qrCodeSize, qrCodeSize, hints);

        writeToStream(bitMatrix, imageFormat, stream, hasLogo);
    }

    public static class LogoConfig{
        public final static Color DEFAULT_BORDERCOLOR = Color.WHITE;    // logo默认边框颜色
        public final static int DEFAULT_BORDER = 5; // logo默认边框宽度
        public final static int DEFAULT_LOGOPART = 5;   // logo大小默觉得照片的1/5
        private final static int border = DEFAULT_BORDER;  // 默认边框宽度
        private final Color borderColor;    // 边框颜色
        private final int logoPart; //  边框外围宽度

        /**
         * 二维码无參构造函数 默认设置Logo图片底色白色宽度2
         */
        public LogoConfig() {
            this(DEFAULT_BORDERCOLOR, DEFAULT_LOGOPART);
        }

        /**
         * 二维码有參构造函数
         *
         * @param borderColor 边框颜色
         * @param logoPart 边框宽度
         */
        public LogoConfig(Color borderColor, int logoPart) {
            // 设置边框
            this.borderColor = borderColor;
            // 设置边框宽度
            this.logoPart = logoPart;
        }

        /**
         * 获取边框颜色
         *
         * @return 获取边框颜色
         */
        public Color getBorderColor() {
            return borderColor;
        }

        /**
         * 获取边框
         *
         * @return 获取边框
         */
        public int getBorder() {
            return border;
        }

        /**
         * 外围边宽
         *
         * @return 外围边宽
         */
        public int getLogoPart() {
            return logoPart;
        }
    }
}
